package com.app.web.socketio

import com.corundumstudio.socketio.AckCallback
import com.corundumstudio.socketio.AckRequest
import com.corundumstudio.socketio.HandshakeData
import com.corundumstudio.socketio.SocketIOClient
import com.corundumstudio.socketio.annotation.OnConnect
import com.corundumstudio.socketio.annotation.OnDisconnect
import com.corundumstudio.socketio.annotation.OnEvent
import com.corundumstudio.socketio.namespace.Namespace
import com.corundumstudio.socketio.protocol.Packet
import com.corundumstudio.socketio.protocol.PacketType
import com.frame.filter.SessionStore
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.apache.shiro.session.Session
import org.springframework.stereotype.Component
/**
 * Created by three on 14-9-26.
 */
@CompileStatic
@TypeChecked
@Component
class DemoEventListener {



    private void checkJsession(HandshakeData data){
        String cookies = data.getHeaders().get("Cookie")
        String[] cookieArray = cookies.substring(1, cookies.length()-1).split(";")
        for(String cookie: cookieArray) {
            String[] kv = cookie.trim().split("=");
            if("JSESSIONID".equals(kv[0])) {
                Session session =  SessionStore.get(kv[1]);
                session.touch()
            }
        }
    }

    @OnConnect
    public void onConnectHandler(SocketIOClient client) {
        println("客户端连接: "+client.sessionId)
        String cookie = client.handshakeData.headers.get("Cookie")
        Session session =  SessionStore.currentSession();
        session.touch()
    }

    @OnDisconnect
    public void onDisconnectHandler(SocketIOClient client) {
        // 溢出房间
        for(String room: client.getAllRooms()){
            Namespace ns = client.getNamespace() as Namespace;
            Packet data = new Packet(PacketType.MESSAGE);
            data.setSubType(PacketType.EVENT);
            data.setName("leaveRoom");
            data.setData(Arrays.asList("用户离开"+client.getSessionId()));
            ns.dispatch(room, data)
            client.leaveRoom(room);
        }
        println("客户端断开")
    }

    @OnEvent("ackevent1")
    public void onAck1(final SocketIOClient client, String data, final AckRequest ackRequest) {

        checkJsession(client.handshakeData);

        data = URLDecoder.decode(data, "UTF-8");
        // check is ack requested by client,
        // but it's not required check
        if (ackRequest.isAckRequested()) {
            // send ack response with data to client
            ackRequest.sendAckData("数据接受到："+new String(data.getBytes(), "UTF-8"));
        }

        // send message back to client with ack callback WITH data
        String sendData = "发送数据: "+new String(data.getBytes(), "UTF-8");
        System.out.println(sendData);
        client.sendEvent("ackevent2", new AckCallback<String>(String.class) {
            @Override
            public void onSuccess(String result) {
                System.out.println("ack from client: " + client.getSessionId() + " data: " + result);
            }
        }, sendData);
    }

    @OnEvent("joinRoom")
    public void joinRoom(final SocketIOClient client, String room, final AckRequest ackRequest) {
        checkJsession(client.handshakeData);
        room = URLDecoder.decode(room, "UTF-8");

        client.joinRoom(room);
        Namespace ns = client.getNamespace() as Namespace;
        Packet data = new Packet(PacketType.MESSAGE);
        data.setSubType(PacketType.EVENT);
        data.setName("addUser");
        data.setData(Arrays.asList("新用户加入"+client.getSessionId()));
        ns.dispatch(room, data)

        ackRequest.sendAckData(new String(room.getBytes(), "UTF-8")+" 房间加入成功");
    }
}
